﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;

namespace mamnontuoitho7.AppCode
{
    public class ThumbnailClass
    {
        Album _album = new Album();
        public ThumbnailClass()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        /// <summary>
        /// Upload Image and thumbnail
        /// </summary>
        /// <param name="fileUpload">Image Upload</param>
        /// <param name="FilePath"></param>
        /// <param name="seoId"></param>
        /// <param name="seoName"></param>
        /// <param name="size"></param>
        /// <param name="saveSource"></param>
        /// <param name="thumbnail">Create thumbnail of not</param>
        /// <returns></returns>
        public string UploadImage(FileUpload fileUpload, String FilePath, String seoId, String seoName, int size, Boolean saveSource, bool thumbnail)
        {
            String SEOName = standardImageName(filter(seoName));
            String SEOID = standardImageName(filter(seoId));
            System.Drawing.Image image = System.Drawing.Image.FromStream(fileUpload.PostedFile.InputStream);
            string ext = Path.GetExtension(fileUpload.FileName).ToLower().Trim();
            //string FilePath = Request.PhysicalApplicationPath + "Images/";
            string LocalFile = "";
            string filename = SEOID;
            filename = filename.Length > 70 ? filename.Substring(0, 70) : filename;
            LocalFile = FilePath + filename + ext;

            if (saveSource)
            {
                if (File.Exists(LocalFile))
                    File.Delete(LocalFile);  //save the image into localfile location
                fileUpload.SaveAs(LocalFile);  //after that create syntax insert the image name into database for later use
            }

            if (thumbnail)
            {
                ////Creating Thumbnail method
               // float imgWidth = 356;
               // float imgHeight = 211;

                float imgWidth = image.PhysicalDimension.Width;
                float imgHeight = image.PhysicalDimension.Height;

                //////// tạo hình lớn trong thu muc photo; thu nhỏ lại nếu wa lớn với 1canh là 600
                int size2 = 250;
                float imgSize1 = imgHeight < imgWidth ? imgHeight : imgWidth;
                //the approximately pixel size of thumbnail image is 150 x 150 based on ratio             
                float imgResize1 = imgSize1 <= size2 ? (float)1.0 : size2 / imgSize1;

                float imgWidth1 = imgWidth * imgResize1;
                float imgHeight1 = imgHeight * imgResize1;


                //float imgWidth = image.PhysicalDimension.Width;
                //float imgHeight = image.PhysicalDimension.Height;
                //float imgSize = imgHeight < imgWidth ? imgHeight : imgWidth;
                ////the approximately pixel size of thumbnail image is 150 x 150 based on ratio             
                //float imgResize = imgSize <= size ? (float)1.0 : size / imgSize;
                //imgWidth *= imgResize; 
                //imgHeight *= imgResize;  
                //generating the thumbnail           
                System.Drawing.Image thumb1 = image.GetThumbnailImage((int)imgWidth1, (int)imgHeight1, delegate() { return false; }, (IntPtr)0);
                //save the thumbnail image into directory 
                string FilePathThumb = FilePath + "thumbnail/";
                LocalFile = FilePathThumb + filename + ext;
                if (File.Exists(LocalFile))
                    File.Delete(LocalFile);
                thumb1.Save(LocalFile);
            }

            return filename + ext;
        }
        /// <summary>
        /// create folder and upload album topic image
        /// </summary>
        /// <param name="fileUpload"></param>
        /// <param name="FilePath"></param>
        /// <param name="seoId"></param>
        /// <param name="seoName"></param>
        /// <param name="size"></param>
        /// <param name="saveSource"></param>
        /// <param name="thumbnail"></param>
        /// <returns></returns>
        public string UploadAlbumTopicImage(FileUpload fileUpload, String FilePath, String seoId, String seoName, String productID)
        {
            _album.CreateAlbumFolder(productID, FilePath);

            String SEOName = standardImageName(filter(seoName));
            String SEOID = standardImageName(filter(seoId));
            System.Drawing.Image image = System.Drawing.Image.FromStream(fileUpload.PostedFile.InputStream);
            string ext = Path.GetExtension(fileUpload.FileName).ToLower().Trim();
            string filename = SEOID;
            filename = filename.Length > 70 ? filename.Substring(0, 70) : filename;
           
                ////Creating Thumbnail method
                //float imgWidth = 200;
                //float imgHeight = 150;


                float imgWidth = image.PhysicalDimension.Width;
                float imgHeight = image.PhysicalDimension.Height;

                //////// tạo hình lớn trong thu muc photo; thu nhỏ lại nếu wa lớn với 1canh là 600
                int size = 150;
                float imgSize1 = imgHeight < imgWidth ? imgHeight : imgWidth;
                //the approximately pixel size of thumbnail image is 150 x 150 based on ratio             
                float imgResize1 = imgSize1 <= size ? (float)1.0 : size / imgSize1;

                float imgWidth1 = imgWidth * imgResize1;
                float imgHeight1 = imgHeight * imgResize1;
               

                //float imgWidth = image.PhysicalDimension.Width;
                //float imgHeight = image.PhysicalDimension.Height;
                //float imgSize = imgHeight < imgWidth ? imgHeight : imgWidth;
                ////the approximately pixel size of thumbnail image is 150 x 150 based on ratio             
                //float imgResize = imgSize <= size ? (float)1.0 : size / imgSize;
                //imgWidth *= imgResize; 
                //imgHeight *= imgResize;  
                //generating the thumbnail           
                System.Drawing.Image thumb1 = image.GetThumbnailImage((int)imgWidth1, (int)imgHeight1, delegate() { return false; }, (IntPtr)0);
                //save the thumbnail image into directory 
                string FilePathThumb = FilePath + "album-"+productID+"/";
                string LocalFile = FilePathThumb + filename + ext;
                if (File.Exists(LocalFile))
                    File.Delete(LocalFile);
                thumb1.Save(LocalFile);

            return filename + ext;
        }



        /// <summary>
        /// upload new topic thumbnail for existed album
        /// </summary>
        /// <param name="fileUpload"></param>
        /// <param name="FilePath"></param>
        /// <param name="seoId"></param>
        /// <param name="seoName"></param>
        /// <param name="size"></param>
        /// <param name="saveSource"></param>
        /// <param name="thumbnail"></param>
        /// <returns></returns>
        public string UploadImage(FileUpload fileUpload, String FilePath, String seoId, String seoName, String productID)
        {
            String SEOName = standardImageName(filter(seoName));
            String SEOID = standardImageName(filter(seoId));
            System.Drawing.Image image = System.Drawing.Image.FromStream(fileUpload.PostedFile.InputStream);
            string ext = Path.GetExtension(fileUpload.FileName).ToLower().Trim();
            string filename = SEOID;
            filename = filename.Length > 70 ? filename.Substring(0, 70) : filename;

            ////Creating Thumbnail method
          //  float imgWidth = 200;
           // float imgHeight = 150;


            float imgWidth = image.PhysicalDimension.Width;
            float imgHeight = image.PhysicalDimension.Height;

            //////// tạo hình lớn trong thu muc photo; thu nhỏ lại nếu wa lớn với 1canh là 600
            int size = 150;
            float imgSize1 = imgHeight < imgWidth ? imgHeight : imgWidth;
            //the approximately pixel size of thumbnail image is 150 x 150 based on ratio             
            float imgResize1 = imgSize1 <= size ? (float)1.0 : size / imgSize1;

            float imgWidth1 = imgWidth * imgResize1;
            float imgHeight1 = imgHeight * imgResize1;

            System.Drawing.Image thumb1 = image.GetThumbnailImage((int)imgWidth1, (int)imgHeight1, delegate() { return false; }, (IntPtr)0);
            //save the thumbnail image into directory 


            string LocalFile = FilePath + filename + ext;
            if (File.Exists(LocalFile))
                File.Delete(LocalFile);
            thumb1.Save(LocalFile);

            return filename + ext;
        }

        public static string standardImageName(string name)
        {
            return (name.Replace(' ', '-').Replace('.', '-').Replace('/', '-').Replace('+', '-').Replace('*', '-').Replace('?', '-').Replace('!', '-').Replace('@', '-').Replace('~', '-').Replace('#', '-').Replace('$', '-').Replace('%', '-').Replace('^', '-').Replace('(', '-').Replace(')', '-').Replace('=', '-').Replace('|', '-').Replace('{', '-').Replace('}', '-').Replace(':', '-').Replace('"', '-').Replace(';', '-').Replace('<', '-').Replace('>', '-').Replace("'", "-").Replace("]", "-").Replace("[", "-").Replace("\\", "-").Replace(",", "-").Replace("“", "").Replace("”", "").Replace("_", "-")).ToLower();              
        }

        private static readonly string[] VietNamChar = new string[] 
    { 
        "aAeEoOuUiIdDyY", 
        "áàạảãâấầậẩẫăắằặẳẵ", 
        "ÁÀẠẢÃÂẤẦẬẨẪĂẮẰẶẲẴ", 
        "éèẹẻẽêếềệểễ", 
        "ÉÈẸẺẼÊẾỀỆỂỄ", 
        "óòọỏõôốồộổỗơớờợởỡ", 
        "ÓÒỌỎÕÔỐỒỘỔỖƠỚỜỢỞỠ", 
        "úùụủũưứừựửữ", 
        "ÚÙỤỦŨƯỨỪỰỬỮ", 
        "íìịỉĩ", 
        "ÍÌỊỈĨ", 
        "đ", 
        "Đ", 
        "ýỳỵỷỹ", 
        "ÝỲỴỶỸ"
    };
        public static string filter(string str)
        {
            //Thay thế và lọc dấu từng char      
            for (int i = 1; i < VietNamChar.Length; i++)
            {
                for (int j = 0; j < VietNamChar[i].Length; j++)
                    str = str.Replace(VietNamChar[i][j], VietNamChar[0][i - 1]);
            }
            return str;
        }


        /// <summary>
        /// Resize and upload image to server
        /// </summary>
        /// <param name="fileUp"></param>
        /// <param name="fullImagePath">path to save </param>
        /// <param name="imageName"></param>
        /// <param name="imageHeight"></param>
        /// <param name="imageWidth"></param>
        /// <returns>Ex:Nguyen-Thi-2.jpg</returns>
        public String UploadImage2(FileUpload fileUp, String fullImagePath, String imageName, int imageHeight, int imageWidth, String oldImage)
        {
            string fileExtension = "";
            string newImage = "";
            try
            {

                imageName = ThumbnailClass.filter(imageName);
                imageName = ThumbnailClass.standardImageName(imageName);
                
                fileExtension = Path.GetExtension(fileUp.FileName).ToLower().Trim();
                newImage = imageName + "-" + DateTime.Now.Ticks + fileExtension;


                if (fileExtension == ".jpg" || fileExtension == ".gif" || fileExtension == ".jpeg" || fileExtension == ".png" || fileExtension == ".bmp" || fileExtension == ".tiff")
                {
                    byte[] data = ImageMedia.Create(fileUp.FileBytes).Resize(imageWidth, imageHeight).ToByteArray();
                    FileStream file = File.Create(fullImagePath + newImage);
                    file.Write(data, 0, data.Length);
                    file.Close();

                    //Delete old image
                    if (oldImage != newImage && oldImage != "")
                    {
                        string LocalFile = fullImagePath + oldImage;
                        if (File.Exists(LocalFile))
                            File.Delete(LocalFile);
                    }

                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex.Message);
                return "";
            }
            return newImage;
        }

    }
}